package com.lwq.imserver.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2022/2/7 9:06
 */
@Component
public class MongoUtil<T> {

    @Autowired
    private MongoTemplate mongoTemplate;

    public void update(T t, String id) {
        Update update = new Update();
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                if ("serialVersionUID".equals(field.getName())
                        || "id".equals(field.getName())) {
                    continue;
                }
                if (field.get(t) != null) {
                    update.set(field.getName(), field.get(t));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        mongoTemplate.updateFirst(new Query(Criteria.where("id").is(id)), update, t.getClass());
    }
}
